<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 

/**
 * Block
 */
class Core_Block extends Core_Entity {
	
	// template
	// layout
	// parent
	// childs: array
	// name_in_layout
	
	// get/set/unset child
	// render
	// renderChild

	protected $_childs = array();
	
	public function append($block) {
		$name = $block->getName();
		$this->_childs[] = $name;
		$block->setParent($this->getName());
		return $this;
	}
	
	public function getChild($name='') {
		if ($name=='') {
			$res = array();
			foreach ($this->_childs as $c)
				array_push($res, $this->getLayout()->getBlock($c));
			return $res;
		} else if (in_array($name, $this->_childs)) {
			return $this->getLayout()->getBlock($name);
		}
		return null;
	}

	public function unsetChild($name) {
		if(($key = array_search($name, $this->_childs)) !== false) {
			$this->getLayout()->removeBlock($name);
			unset($this->_childs[$key]);
		}
		return $this;
	}
	
	public function renderChild($name='') {
		if ($name=='') {
			// render all child
			foreach ($this->_childs as $block) {
				$b = $this->getLayout()->getBlock($block);
				if ($b) $b->render();
			}
		} else {
			$b = $this->getChild($name);
			if ($b) $b->render();
		}
	}
	
	public function render() {
		$this->_beforeRender();
		if ($this->getTemplate()) {
			App::view($this->getTemplate(), array('self' => $this));
		} else {
			$this->renderChild();
		}
		$this->_afterRender();
	}
	
	public function setLayout($layout) {
		$this->setData('layout', $layout);
		$this->_prepareLayout();
	}

	protected function _prepareLayout() { }

	protected function _beforeRender() { }

	protected function _afterRender() { }
}